package com.rain.rainspringboot3.encryption.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.rain.rainspringboot3.encryption.annotation.EnableEncryption;
import com.rain.rainspringboot3.encryption.entity.User;
import com.rain.rainspringboot3.encryption.entity.UserDTO;
import com.rain.rainspringboot3.encryption.entity.UserVO;
import com.rain.rainspringboot3.encryption.enums.CRUDType;
import com.rain.rainspringboot3.encryption.mapper.User1Mapper;
import com.rain.rainspringboot3.encryption.mapper.UserDTOMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现
 */
@Service
public class User1Service extends ServiceImpl<User1Mapper, User> {
    
    @Autowired
    private User1Mapper user1Mapper;
    
    @Autowired
    private UserDTOMapper userDTOMapper;
    
    /**
     * 创建用户（自动加密敏感数据）
     */
    @EnableEncryption(type = CRUDType.INSERT)
    public boolean createUser(UserDTO userDTO) {
        // 转换DTO到Entity
        User user= userDTOMapper.toUserVO(userDTO);
        // 保存用户（加密操作由AOP自动处理）
       return user1Mapper.insert(user)>0;
    }
    
    /**
     * 获取用户详情（自动解密敏感数据）
     */
    @EnableEncryption(type = CRUDType.SELECT)
    public UserVO getUserById(Long id) {
        User user = user1Mapper.selectById(id);
        if (user == null) {
            return null;
        }
        // 转换为VO（解密操作由AOP自动处理）
        return userDTOMapper.toUserVO(user);
    }
    
    /**
     * 获取所有用户（测试批量解密功能）
     */
    @EnableEncryption(type = CRUDType.SELECT)
    public List<UserVO> getAllUsers() {
        List<User> users = user1Mapper.findAll();
        return users.stream().map(userDTOMapper::toUserVO).toList();
    }
    
    /**
     * 根据用户名查询用户
     */
    @EnableEncryption
    public UserVO getUserByUsername(String username) {
        User user = user1Mapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        return userVO;
    }
}